package com.company.hotel.shiro.realm;

import com.company.hotel.model.pojo.Module;
import com.company.hotel.model.pojo.Role;
import com.company.hotel.model.pojo.User;
import com.company.hotel.service.UsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {
    //先要从数据库中找到对应的角色的信息和权限信息
    @Autowired
    public UsersService userService;
    /**
     * 获取用户权限信息
     * 在用户访问某个资源时调用该方法判断用户是否有权限，前提是用户的请求需要某个角色的权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        // 准备返回数据
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 得到用户
        User user = (User) principal.getPrimaryPrincipal();
        Set<Role> roles = user.getRoles();
        Set<String> u = new HashSet<String>();
        Set<String> m = new HashSet<String>();
        if(roles.size()>0){
            for(Role role : roles){
                u.add(role.getrName());
                if(role.getModules().size()>0){
                    Set<Module> modules = role.getModules();
                    for(Module module: modules){
                        m.add(module.getmName());
                    }
                }
            }
        }
        authorizationInfo.setRoles(u);
        authorizationInfo.addStringPermissions(m);
        return authorizationInfo;
    }

    /**
     * 获取用户认证信息
     * 当判断请求为登录请求时会自动调用该认证方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // TODO Auto-generated method stub
        String userName = (String) token.getPrincipal();
        String passWord = new String((char[])token.getCredentials());
        HashMap<String,String> hashMap = new HashMap<String, String>();
        hashMap.put("userName", userName);
        hashMap.put("passWord", passWord);
        List<User> userlist = userService.findByUserName(hashMap);
        if(userlist.size()>0){
            //判断用户是否被锁定
            int locked = userlist.get(0).getLocked();
            if(locked==1){
                //被锁
                throw new LockedAccountException();
            }else{
                //返回认证成功的用户
                return new SimpleAuthenticationInfo(userlist.get(0),passWord,getName());
            }
        }else{
            //账号异常
            throw new UnknownAccountException();
        }
    }
}
